package org.apache.log4j.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;

import com.alibaba.fastjson.JSON;

public class MyLog4jJDBCAppender extends JDBCAppender {
	private static Set<String> sqls=new HashSet<String>();
	private static long sqlsize=0;
	private static long sqlBufferSize=500;
	private Connection con = null;
	public void setSqlBufferSize(long sqlBufferSize) {
		MyLog4jJDBCAppender.sqlBufferSize = sqlBufferSize*1024;
	}
	public  long getSqlBufferSize() {
		return sqlBufferSize;
	}
	@Override
	protected void execute(String sql) throws SQLException {
		// TODO Auto-generated method stub
		if(sql==null)return;
		int size=sql.length();
		if((size+sqlsize)>=sqlBufferSize){
			pushDb();
			sqlsize=size;
		}else{
			sqls.add(sql);
			sqlsize+=size;
		}
	}
	private void pushDb() throws SQLException{
	    if(isClosed())
	        {
	        if (!DriverManager.getDrivers().hasMoreElements())
	   	     	setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
	        	con = DriverManager.getConnection(databaseURL, databaseUser,databasePassword);
	        }
	    	Statement stmt = null;
	         try { 
	        	 stmt = con.createStatement();
	        	 for (String sql : sqls) {
	        		 stmt.addBatch(sql.trim());
				}
	 	       int[] num = stmt.executeBatch();
	 	       System.out.println(JSON.toJSON(num));
			}catch(SQLException e){
				e.printStackTrace();
			}
	         finally{

	     		sqls.clear();
				if(stmt!=null)stmt.close();
			}
	}
	private boolean isClosed(){
		try{
		if(con==null||con.isClosed())
			return true;
		con.prepareStatement("SELECT NULL FROM DUAL").executeQuery();
		}catch(Exception e){return true;}
		return false;
	}
}
